package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        InputStream inputStream = file.getInputStream();

        String originalFilename = file.getOriginalFilename();
        String png = StringUtils.getFilenameExtension(originalFilename);
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String date = new DateTime().toString("yyyy/MM/dd");
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())

                //这里上传到minio的路径少加了一个“/”

                .object(date + "/" + fileName + "." + png)
                .stream(inputStream, file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);

        log.info(minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + date + "/" + fileName + "." + png);

        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + date + "/" + fileName + "." + png;

    }
}
